package io.renren.modules.generator.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vortex.tool.httpclient.HttpMethodName;
import com.vortex.tool.httpclient.Protocol;
import com.vortex.tool.httpclient.VtxHttpClient;
import com.vortex.tool.httpclient.request.VtxHttpRequest;
import com.vortex.tool.httpclient.sign.VtxV1Signer;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.constant.DeviceFinal;
import io.renren.modules.generator.dao.DeviceTianruiWaterDao;
import io.renren.modules.generator.entity.DeviceTianruiWaterEntity;
import io.renren.modules.generator.service.DeviceTianruiWaterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("deviceTianruiWaterService")
public class DeviceTianruiWaterServiceImpl extends ServiceImpl<DeviceTianruiWaterDao, DeviceTianruiWaterEntity> implements DeviceTianruiWaterService {

    private static Logger logger = LoggerFactory.getLogger(DeviceTianruiWaterServiceImpl.class);
    @Autowired
    private DeviceTianruiWaterDao deviceTianruiWaterDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DeviceTianruiWaterEntity> page = this.page(
                new Query<DeviceTianruiWaterEntity>().getPage(params),
                new QueryWrapper<DeviceTianruiWaterEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void putData() {
        VtxHttpRequest request = new VtxHttpRequest();
        request.withHttpMethod(HttpMethodName.GET);
        request.withParams("deviceIds",DeviceFinal.device_water_code_arr);//团队水质
        try {
            request.withUri(new URI(DeviceFinal.device_url));
            VtxHttpClient client = new VtxHttpClient(DeviceFinal.credential, new VtxV1Signer(), Protocol.HTTP);
            String result = client.execute(request);
            logger.info("------------result:"+result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            DeviceTianruiWaterEntity deviceTianruiWaterEntity;
            for (int j = 0; j < DeviceFinal.device_water_code_arr.length; j++) {
                JSONArray jsonArray = jsonObject.getJSONObject("ret").getJSONArray(DeviceFinal.device_water_code_arr[j]);
                for (int i = 0; i < jsonArray.size(); i++) {
                    QueryWrapper<DeviceTianruiWaterEntity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("device_code",jsonArray.getJSONObject(i).getString("code"))
                            .eq(
                                    "create_time",
                                    DateUtils.longToDate(
                                            Long.parseLong(jsonArray.getJSONObject(i).getString("time")),"yyyy-MM-dd HH"
                                    )
                            ).eq("device_adress_type",DeviceFinal.device_water_code_arr[j]);
                    deviceTianruiWaterDao.delete(queryWrapper);
                    deviceTianruiWaterEntity = new DeviceTianruiWaterEntity();
                    deviceTianruiWaterEntity.setDeviceAdressType(DeviceFinal.device_water_code_arr[j]);
                    deviceTianruiWaterEntity.setDeviceCode(jsonArray.getJSONObject(i).getString("code"));
                    deviceTianruiWaterEntity.setDeviceIndexName(DeviceFinal.waterQuotaMap.get(jsonArray.getJSONObject(i).getString("code")));
                    deviceTianruiWaterEntity.setCreateTime(
                            DateUtils.longToDate(Long.parseLong(jsonArray.getJSONObject(i).getString("time")),"yyyy-MM-dd HH")
                    );
                    deviceTianruiWaterEntity.setDeviceValue(jsonArray.getJSONObject(i).getString("value"));
                    deviceTianruiWaterDao.insert(deviceTianruiWaterEntity);
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object chartlist(String dateStr) {
        JSONObject jsonObject = new JSONObject(true);
        try {
            DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = fmt.parse(dateStr);
            JSONArray jsonArray1;
            DeviceTianruiWaterEntity deviceTianruiWaterEntity;
            JSONArray jsonArray2;
            for (int j = 0; j < DeviceFinal.device_water_code_arr.length; j++) {
                jsonArray1 = new JSONArray();
                JSONObject jsonObject2 = new JSONObject();
                for(Map.Entry<String, String> entry : DeviceFinal.waterQuotaMap.entrySet()){
                    jsonArray2 = new JSONArray();
                    String mapKey = entry.getKey();
                    String mapValue = entry.getValue();
                    Calendar calendarZero = Calendar.getInstance();
                    calendarZero.setTime(now);
                    calendarZero.set(Calendar.HOUR_OF_DAY, 0);
                    calendarZero.set(Calendar.MINUTE, 0);
                    calendarZero.set(Calendar.SECOND, 0);
                    Date zero = calendarZero.getTime();
                    QueryWrapper<DeviceTianruiWaterEntity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("device_code",mapKey)
                            .eq("create_time",zero)
                            .eq("device_adress_type",DeviceFinal.device_water_code_arr[j])
                    ;
                    deviceTianruiWaterEntity = deviceTianruiWaterDao.selectOne(queryWrapper);
                    if(Objects.isNull(deviceTianruiWaterEntity)){
                        jsonArray2.add("0");
                    }else{
                        jsonArray2.add(deviceTianruiWaterEntity.getDeviceValue());
                    }
//                    Date day=new Date();
//                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
                    SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    String s = df.format(now);
                    SimpleDateFormat hourFormat=new SimpleDateFormat("HH");
//                    Date date = fmt.parse(dateStr);
                    Date date = zero;
                    GregorianCalendar calendar = new GregorianCalendar();
                    int hour = calendar.get(Calendar.HOUR_OF_DAY);
                    for (int i = 0; i < DateUtils.getHour(dateStr); i++) {//从1点开始到当前时间的小时
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(date);
                        cal.add(Calendar.HOUR, 1);
                        date = cal.getTime();
                        String s1 = format.format(date);
                        logger.info("--------"+s1+"---------");
                        queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("device_code",mapKey)
                                .eq("create_time",date)
                                .eq("device_adress_type",DeviceFinal.device_water_code_arr[j]);
                        deviceTianruiWaterEntity = deviceTianruiWaterDao.selectOne(queryWrapper);
                        if(Objects.isNull(deviceTianruiWaterEntity)){
                            jsonArray2.add("0");
                        }else{
                            jsonArray2.add(deviceTianruiWaterEntity.getDeviceValue());
                        }
                    }
                    jsonObject2.put(mapKey,jsonArray2);
                }
                jsonArray1.add(jsonObject2);
                jsonObject.put(DeviceFinal.device_water_code_arr[j],jsonArray1);
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

}